package cn.yq.aio.ui.main.xueyang;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.creative.FingerOximeter.FingerOximeter;
import com.creative.FingerOximeter.IFingerOximeterCallBack;
import com.creative.base.BaseDate;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.List;

import cn.yq.aio.base.BaseFragment;
import cn.yq.aio.base.MyApp;
import cn.yq.aio.databinding.FragmentXueYangBinding;
import cn.yq.aio.ui.main.xueyang.sdk.BLEHelper;
import cn.yq.aio.ui.main.xueyang.sdk.BLEManager;
import cn.yq.aio.ui.main.xueyang.sdk.BluetoothLeService;
import cn.yq.aio.ui.main.xueyang.sdk.ReaderBLE;
import cn.yq.aio.ui.main.xueyang.sdk.SenderBLE;
import cn.yq.aio.utils.BleUtils;
import cn.yq.aio.utils.SystemUtils;
import cn.yq.aio.utils.recycler.TShow;

/**
 * @AUTHOR YangLu
 * @Time 2021-03-25
 * @todo 血氧
 */
public class XueYangFragment extends BaseFragment {

    public XueYangFragment() {
        // Required empty public constructor
    }

    public static XueYangFragment newInstance() {
        XueYangFragment xueYangFragment = new XueYangFragment();
        return xueYangFragment;
    }

    FragmentXueYangBinding binding;
    BleUtils bleUtils;

    private FingerOximeter mFingerOximeter;
    private BluetoothLeService mBluetoothLeService;
    private ServiceConnection mServiceConnection;
    private BluetoothDevice targetDevice;
    private BLEHelper mBleHelper;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentXueYangBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding.getRoot().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (binding.tipsXueYangFrg.getVisibility() == View.VISIBLE) {
                    binding.tipsXueYangFrg.setVisibility(View.GONE);
                }
                return false;
            }
        });
        binding.rightMain.titleRightMainFrg.setText("血氧测量");
        binding.rightMain.measureRightMainFrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkStart();
            }
        });

        binding.numXueYangFrg.setText("--");
        binding.xlbXueYangFrg.setText("--");
    }

    private void checkStart() {
        if (!getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            TShow.show("该设备不支持蓝牙");
            return;
        }
        if (bleUtils != null) {
            TShow.show("等待本次测量完成再开始监测");
            return;
        }
        XXPermissions.with(this).permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (!SystemUtils.isGpsEnable()) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                            builder.setCancelable(false);
                            builder.setTitle("提示")
                                    .setIcon(android.R.drawable.ic_menu_info_details)
                                    .setMessage("蓝牙链接需要开启GPS定位")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent =
                                                    new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivity(intent);
                                        }
                                    });
                            builder.show();
                            return;
                        }
                        readyStart();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        TShow.show("蓝牙链接需要开启定位权限");
                    }
                });
    }

    private void readyStart() {
        showTips("开始扫描设备...");//mGattUpdateReceiver 回调

        bleUtils = new BleUtils(getActivity(), new BleUtils.CallBack() {
            @Override
            public boolean isNeedDevice(String bleDeviceName) {
                return "PC-60NW-1".equalsIgnoreCase(bleDeviceName) ||
                        "POD".equalsIgnoreCase(bleDeviceName) ||
                        "PC-68B".equalsIgnoreCase(bleDeviceName) ||
                        "Wrist-100".equalsIgnoreCase(bleDeviceName);
            }

            @Override
            public boolean needConnect(BluetoothDevice td) {
                showTips("已找到设备，准备连接...");
                targetDevice = td;
                Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
                initConnection();
                getActivity().startService(gattServiceIntent);
                getActivity().bindService(gattServiceIntent, mServiceConnection,
                        getContext().BIND_AUTO_CREATE);
                Log.e("1111", "启动服务：" + td.getName());
                return false;
            }

            @Override
            public boolean isNeedService(String uuid) {
                return false;
            }

            @Override
            public boolean isNeedCharacteristic(String uuid) {
                return false;
            }

            @Override
            public void findCharacteristic(BluetoothGattCharacteristic characteristic) {

            }

            @Override
            public void onReceiveValue(byte[] data) {

            }

            @Override
            public void breakConnect() {

            }
        });
        bleUtils.open(true);
    }

    private void initConnection() {
        mServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder service) {
                Log.e("1111", "启动服务成功");
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    Log.e("xueyang", "Unable to initialize Bluetooth");
                    //Toast.makeText(mContext, "Unable to initialize Bluetooth", Toast
                    // .LENGTH_SHORT).show();
                    return;
                }
                mBleHelper = new BLEHelper(mBluetoothLeService);
                // Automatically connects to the device upon successful start-up
                // initialization.
                mBluetoothLeService.connect(targetDevice.getAddress());
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        //监听蓝牙
        getContext().registerReceiver(mGattUpdateReceiver, BLEManager.makeGattUpdateIntentFilter());
    }

    @Override
    public void onStop() {
        super.onStop();
        getContext().unregisterReceiver(mGattUpdateReceiver);
        end();
    }

    public final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                showTips("蓝牙连接成功！,请开始测试");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                TShow.show("蓝牙连接已断开");
                end();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on
                // theuser interface.
                // showAllCharacteristic();

            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //Toast.makeText(MainActivity.this,intent.getStringExtra(BluetoothLeService
                // .EXTRA_DATA),Toast.LENGTH_SHORT).show();

            } else if (BluetoothLeService.ACTION_SPO2_DATA_AVAILABLE.equals(action)) {
                //byte[] data =intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                //Log.d(TAG, "MainActivity received:"+Arrays.toString(data));

            } else if (BluetoothLeService.ACTION_CHARACTER_NOTIFICATION.equals(action)) {
                //接收到数据
                startFingerOximeter();
            } else if (BLEManager.ACTION_FIND_DEVICE.equals(action)) {
                showTips("找到设备，开始连接...");
            } else if (BLEManager.ACTION_SEARCH_TIME_OUT.equals(action)) {
                showTips("扫描设备超时，请重试");
            } else if (BLEManager.ACTION_START_SCAN.equals(action)) {

            }
        }
    };

    //接受数据
    private void startFingerOximeter() {
        if (mBleHelper != null) {
            mFingerOximeter = new FingerOximeter(new ReaderBLE(mBleHelper),
                    new SenderBLE(mBleHelper),
                    new FingerOximeterCallBack());
            mFingerOximeter.Start();
            mFingerOximeter.SetWaveAction(true);
        }
    }

    private void end() {
        if (mFingerOximeter != null)
            mFingerOximeter.Stop();
        mFingerOximeter = null;
        if (bleUtils != null)
            bleUtils.close();
        bleUtils = null;
        if (mServiceConnection != null) {
            Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
            getActivity().unbindService(mServiceConnection);
            getActivity().stopService(gattServiceIntent);
        }
        mServiceConnection = null;
    }

    /**
     * 收到的血氧仪数据
     * received FingerOximeter of data
     */
    class FingerOximeterCallBack implements IFingerOximeterCallBack {

        @Override
        public void OnGetSpO2Param(final int nSpO2,
                                   final int nPR,
                                   float fPI,
                                   final boolean nStatus,
                                   int nMode,
                                   float nPower,
                                   int powerLevel) {
            Log.e("xueyang", "nSpO2=" + nSpO2 + " nPR=" + nPR
                    + " fPI=" + fPI + " nPower=" + nPower + " nStatus=" + nStatus
                    + " nMode=" + nMode + " powerLevel=" + powerLevel);
            //拿到数据
            MyApp.getInstance().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (!nStatus) {
                        showTips("测量完成");
                        end();
                        return;
                    }
                    hideTips();
                    binding.numXueYangFrg.setText("" + nSpO2);
                    binding.xlbXueYangFrg.setText("" + nPR);
                }
            });
        }

        //血氧波形数据采样频率：50Hz，每包发送 5 个波形数据，即每 1 秒发送 10 包波形数据
        //参数 waves 对应一包数据
        //spo2 sampling rate is 50hz, 5 wave data in a packet,
        //send 10 packet 1/s. param "waves" is 1 data packet
        @Override
        public void OnGetSpO2Wave(List<BaseDate.Wave> waves) {
            //Log.d(TAG, "wave.size:"+waves.size()); // size = 5
            //myHandler.obtainMessage(MSG_DATA_SPO2_WAVE, waves).sendToTarget();
        }

        @Override
        public void OnGetDeviceVer(final int nHWMajor, int nHWMinor, int nSWMajor, int nSWMinor) {
            MyApp.getInstance().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    TShow.show("获取到设备信息:" + nHWMajor);
                }
            });
        }

        @Override
        public void OnConnectLose() {
            MyApp.getInstance().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    showTips("连接丟失");
                }
            });
        }
    }

    private void showTips(String msg) {
        binding.tipsXueYangFrg.setVisibility(View.VISIBLE);
        binding.tipsXueYangFrg.setText(msg);
    }

    private void hideTips() {
        binding.tipsXueYangFrg.setVisibility(View.GONE);
    }
}
